﻿namespace TradePublish.SysThread.Sys
{
    using log4net;
    using System;
    using System.Data;
    using System.Net;
    using System.Net.Sockets;
    using System.Reflection;
    using System.Text;
    using System.Threading;
    using TradePublish.Dao;
    using System.Collections.Generic;
using System.Collections;
    using TradePublish.Service;
    /// <summary>
    /// 
    /// 客户              服务器端
    /// 编号:READY ---------->
    ///       <---------  dataset 
    /// 
    /// </summary>
    internal class SearchEmailTaskServerThread
    {
        
         private Socket serverSocket;
         private Socket clientSocket;

         private Thread doThread;
         private Thread acceptDataThread;
        private Hashtable  applyUserNames = new Hashtable();//最新一期反查记录的申请人，一次1000条
        private ILog log = null;
        private bool doDBing =false;
        //
        private Thread updateHasSearchEmailThread;//更新已采集标识用的

         public SearchEmailTaskServerThread()
        {
            this.log = log4net.LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
        }

        public void start()
        {
            this.doThread = new Thread(new ThreadStart(this.threadWork));
            this.doThread.IsBackground = true;
            this.doThread.Start();

            this.updateHasSearchEmailThread = new Thread(new ThreadStart(this.updateHasSearchEmailThreadWork));
            this.updateHasSearchEmailThread.IsBackground = true;
            this.updateHasSearchEmailThread.Start();
        }

     
        public void threadWork()
        { 
            getTask(); //获得待搜索的申请人名称

            IPEndPoint ipep = new IPEndPoint(IPAddress.Any, 3001); //监听所以来访IP
            serverSocket = new Socket(ipep.AddressFamily, SocketType.Stream, ProtocolType.Tcp); 
            serverSocket.SetSocketOption(SocketOptionLevel.Socket,SocketOptionName.SendTimeout,160000);
            serverSocket.SetSocketOption(SocketOptionLevel.Socket,SocketOptionName.ReceiveTimeout,160000);
            serverSocket.Bind(ipep); 
            serverSocket.Listen(10); 
            while (true)
            { 
                clientSocket = serverSocket.Accept();
                acceptDataThread = new Thread(new ThreadStart(acceptDataWork)); //接收数据
                acceptDataThread.Start(); 
            }  
        }

        /// <summary>
        /// 
        /// </summary>
        private void getTask()
        {
            if (!doDBing)
            {
                doDBing = true;
                DissentTradeDao dao = new DissentTradeDao();
                applyUserNames = dao.findUnSearchEmailTask();
                doDBing = false;
                //保存到临时文件
                dao.saveTmp(applyUserNames); 
            }
        }
        #region 接收数据的线程工作函数
        private void acceptDataWork()
        {
            Socket s = clientSocket;//客户端信息 
            IPEndPoint ipEndPoint = (IPEndPoint)s.RemoteEndPoint;
            String address = ipEndPoint.Address.ToString();
            String port = ipEndPoint.Port.ToString();
            log.Info(address + ":" + port + " 连接过来了");
            Byte[] inBuffer = new Byte[10240];
            Byte[] outBuffer = new Byte[10240];
            String inBufferStr;
            String outBufferStr;
            try
            {
                s.Receive(inBuffer, 10240, SocketFlags.None);//如果接收的消息为空 阻塞 当前循环  
                inBufferStr = Encoding.UTF8.GetString(inBuffer);
                log.Info(address + ":" + port + "说:" + inBufferStr);
                int clientTaskNo = Convert.ToInt32(inBufferStr.Split(':')[0]);
                // 准备数据发送过去 
                List<String> spliNames = new List<string>();
                StringBuilder outStr = new StringBuilder();
                if (applyUserNames == null || applyUserNames.Count == 0)
                {
                    //木有了，需要从数据库获得
                    getTask(); //获得待搜索的申请人名称
                }
                int count = 0;
                String maxISSUE = "0";
                foreach (DictionaryEntry objDE in applyUserNames)
                {
                    spliNames.Add(objDE.Key.ToString());
                    maxISSUE = objDE.Value.ToString();
                    outStr.Append(objDE.Key.ToString()).Append("\t");
                    count++;
                    if (count >= 10)
                    {
                        break;
                    }
                }
                outBufferStr = maxISSUE+":" + outStr.ToString();//将申请人构造成字符串，每个申请人之间用\t分割
                outBuffer = Encoding.UTF8.GetBytes(outBufferStr);
                log.Info("发送" + address + ":" + port + ">>>>>>" + outBufferStr);
                s.Send(outBuffer, outBuffer.Length, SocketFlags.None);
                //将列表中已分配的数据删除
                foreach (String a in spliNames)
                {
                    applyUserNames.Remove(a);
                }
            }
            catch
            {
                log.Error("客户端:" + address + "已关闭！");
            }
        }
        #endregion
   
            //TcpListener listener = null;
            //int port = 0x235a;
            //IPAddress localaddr = IPAddress.Parse(new IPListDao().getIp());
            //listener = new TcpListener(localaddr, port);
            //this.log.Info("》》》》》》本机IP：" + localaddr);
            //listener.Start();
            //byte[] buffer = new byte[0x400];
            //while (true)
            //{
            //    bool flag = true;
            //    try
            //    {
            //        TimeSpan span;
            //        buffer = new byte[0x400];
            //        DissentTradeDao dao2 = new DissentTradeDao();
            //        DataSet set = null;
            //        DateTime now = new DateTime(0x7dc, 1, 1);
            //        int num2 = 0;
            //        string str2 = null;
            //        goto Label_02AE;
            //    Label_0089:
            //        span = new TimeSpan();
            //        span = (TimeSpan) (DateTime.Now - now);
            //        if ((((set == null) || (set.Tables[0].Rows.Count == 0)) || (num2 >= set.Tables[0].Rows.Count)) && (span.TotalMinutes > 5.0))
            //        {
            //            now = DateTime.Now;
            //            num2 = 0;
            //        }
            //        TcpClient client = listener.AcceptTcpClient();
            //        str2 = null;
            //        NetworkStream stream = client.GetStream();
            //        this.log.Info("<<<<<收到客户端传来的信息：要任务.");
            //        int count = stream.Read(buffer, 0, buffer.Length);
            //        str2 = Encoding.Unicode.GetString(buffer, 0, count);
            //        string s = "";
            //        if (((set == null) || (set.Tables[0].Rows.Count == 0)) || (num2 >= set.Tables[0].Rows.Count))
            //        {
            //            s = "无";
            //        }
            //        else
            //        {
            //            StringBuilder builder = new StringBuilder();
            //            if (num2 >= set.Tables[0].Rows.Count)
            //            {
            //                builder = new StringBuilder("无");
            //            }
            //            else
            //            {
            //                for (int i = num2; i < (num2 + 10); i++)
            //                {
            //                    if (i >= set.Tables[0].Rows.Count)
            //                    {
            //                        num2 = 0;
            //                        set = null;
            //                        break;
            //                    }
            //                    builder.Append(set.Tables[0].Rows[i][0].ToString()).Append(";");
            //                    num2++;
            //                }
            //            }
            //            s = builder.ToString();
            //        }
            //        byte[] bytes = Encoding.Unicode.GetBytes(s);
            //        stream.Write(bytes, 0, bytes.Length);
            //        this.log.Info("<<<<<为客户端节点：" + str2 + "分配任务." + s);
            //        client.Close();
            //    Label_02AE:
            //        flag = true;
            //        goto Label_0089;
            //    }
            //    catch (SocketException exception)
            //    {
            //        this.log.Error(">>>>服务器端读取Email采集任务异常", exception);
            //    }
            //    finally
            //    {
            //        listener.Stop();
            //    }
            //}
        //}

        public void updateHasSearchEmailThreadWork()
        {
            //从临时表中已采集的更新到反查记录，标识申请人已采集
            while(true){
                DissentTradeDao dao = new DissentTradeDao();
                DataSet ds = dao.findHasSearchEmail();
                Int64 maxId = 0;
                if (ds != null && ds.Tables != null && ds.Tables.Count > 0 && ds.Tables[0].Rows != null && ds.Tables[0].Rows.Count > 0)
                {

                    for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                    {
                        try
                        {
                            maxId = Convert.ToInt64(ds.Tables[0].Rows[i]["id"]);
                            dao.setHasSearchEmail(ds.Tables[0].Rows[i]["apply_user_name"].ToString(), ds.Tables[0].Rows[i]["issue"].ToString());
                        }
                        catch (Exception ess)
                        {
                            i--;
                        }
                    }

                    String sql = "delete from APPLU_USER_CONTRACT_TMP where id <=" + maxId;
                    while (true)
                    {
                        DatabaseHelper dbh = new DatabaseHelper();
                        try
                        {
                            log.Debug("<<<<<<<<<--" + sql);
                            dbh.ExecuteNonQuery(sql);
                            return;
                        }
                        catch (Exception exception)
                        { 
                            this.log.Error("设置申请人的邮箱已采集异常，dissent_trade", exception);
                        }
                        finally
                        {
                            dbh.Dispose();
                        }
                        Thread.Sleep(0x1388);
                    }

                }
                else
                {
                    Thread.Sleep(50000);
                }
            } 
        }
    }
}

